package com.controller;

import com.base.AjaxResult;
import com.base.BaseController;
import com.bean.sqlite.api.FreeApiJokes;
import com.bean.sqlite.api.FreeApiQpdh;
import com.bean.sqlite.api.FreeApiRandomRiddle;
import com.service.FreeApiLocalService;
import com.service.FreeApiService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@RestController
@RequestMapping("freeapilocal")
public class FreeApiLocalController extends BaseController {

    @Autowired
    private FreeApiLocalService freeApiLocalService;

    @GetMapping("text")
    public AjaxResult randomText(@Param("type")String type){
        if("开心一笑".equals(type)){
            FreeApiJokes freeApiJokes = freeApiLocalService.getJoke();
            return AjaxResult.success("成功",freeApiJokes);
        }else
        if("奇葩对话".equals(type)){
            FreeApiQpdh freeApiQpdh = freeApiLocalService.getQpdh();
            return AjaxResult.success("成功",freeApiQpdh);
        }else
        if("脑筋急转弯".equals(type)){
            FreeApiRandomRiddle freeApiRandomRiddle = freeApiLocalService.getRiddle();
            return AjaxResult.success("成功",freeApiRandomRiddle);
        }else{

        }
        return null;
    }

    @GetMapping("img")
    public AjaxResult randomImage(@Param("type")String type){
        return AjaxResult.success("成功",freeApiLocalService.getImg(type));
    }

    private final WebClient webClient;

    private static final String ALLOWED_DOMAIN = "http://img5.adesk.com/";

    // 初始化 WebClient
    public FreeApiLocalController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

    @GetMapping("/proxy/image")
    public void proxyImage(
            @RequestParam("url") String url,
            HttpServletResponse response) throws IOException {

        String decodedUrl = java.net.URLDecoder.decode(url, "UTF-8");

        // 白名单校验
        if (!decodedUrl.startsWith(ALLOWED_DOMAIN)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("非法图片链接");
            return;
        }

        // 非阻塞转发请求
        Mono<byte[]> imageMono = webClient.get()
                .uri(decodedUrl)
                .header("Referer", "https://your-domain.com") // 防盗链Referer
                .accept(MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG, MediaType.IMAGE_GIF)
                .retrieve()
                .bodyToMono(byte[].class);

        // 响应给小程序
        imageMono.subscribe(
                imageBytes -> {
                    try {
                        response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 动态获取更准确，这里简化
                        response.setContentLength(imageBytes.length);
                        OutputStream os = response.getOutputStream();
                        os.write(imageBytes);
                        os.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                },
                error -> {
                    try {
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        response.getWriter().write("图片加载失败");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    @GetMapping("video")
    public AjaxResult randomVideo(@Param("type")String type){
        return AjaxResult.success("成功",freeApiLocalService.getVideo());
    }


}
